package com.example.dzdph.service;

import android.content.Context;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.accessibility.AccessibilityWindowInfo;

import androidx.annotation.Nullable;

import com.example.dzdph.tool.UiHandler;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
 *
 */
public abstract class AccessibilityBridge {

    private WindowFilter mWindowFilter;

    private final UiHandler mUiHandler;

    private final Context mContext;

    private final AccessibilityConfig mConfig;

    public static final int MODE_NORMAL = 0;
    public static final int MODE_FAST = 1;

    public static final int FLAG_FIND_ON_UI_THREAD = 1;
    public static final int FLAG_USE_USAGE_STATS = 2;
    public static final int FLAG_USE_SHELL = 4;

    private int mMode = MODE_NORMAL;

    public interface WindowFilter {
        boolean filter(AccessibilityWindowInfo info);
    }

    @Nullable
    public abstract AccessibilityService getService();

    public AccessibilityBridge(Context context, AccessibilityConfig config, UiHandler uiHandler) {
        mConfig = config;
        mUiHandler = uiHandler;
        mConfig.seal();
        mContext = context;
        AccessibilityService.Companion.setBridge(this);
    }

    public List<AccessibilityNodeInfo> windowRoots(){
        AccessibilityService service = getService();
        if (service == null) {
            return Collections.emptyList();
        }
        ArrayList<AccessibilityNodeInfo> roots = new ArrayList<>();
        if (mWindowFilter != null) {
            for (AccessibilityWindowInfo window : service.getWindows()) {
                if (mWindowFilter.filter(window)) {
                    AccessibilityNodeInfo root = window.getRoot();
                    if (root != null) {
                        roots.add(root);
                    }
                }
            }
            return roots;
        }
        if ((mMode & MODE_FAST) != 0) {
            return Collections.singletonList(service.getFastRootInActiveWindow());
        }
        return Collections.singletonList(service.getRootInActiveWindow());
    }
}